<script>

const defaultId = '1'
export default {
  name: 'HomePage',
  data() {
    return {
      fileList: [],
      form: {
        name: null
      }
    }
  },
  created() {
    this.$api.miniProgramHomePage.get(defaultId).then(res => {
      this.form.name = res.data.name
      this.form.id = res.data.id || defaultId
      if (res.data.logo) {
        this.form.logo = res.data.logo
        this.fileList = [{
          url: res.data.logo
        }]
      }
    })
  },
  methods: {
    handleChange(file, fileList) {
      this.fileList = fileList
    },
    async saveHandler() {
      const data = {
        id: this.form.id || defaultId,
        name: this.form.name
      }
      if (this.fileList.length > 0) {
        const file = this.fileList[0]
        if (file.raw) {
          const formData = new FormData()
          formData.append('file', file.raw)
          const urlRes = await this.$api.fileManage.baseUploadData(
            '/energy-carbon/grass-file/file/upload',
            formData
          )
          data.logo = urlRes.data
        } else {
          data.logo = this.form.logo || ''
        }
      }
      const res = await this.$api.miniProgramHomePage.update(data)
      if (Number(res.code) === 1000) {
        this.$message.success(`保存成功！`)
      }
    },
    resetHandler() {
      this.fileList = []
      this.form = {}
    }
  }
}
</script>

<template>
  <div class="CardItems-box">
    <el-row>
      <el-col :span="12">
        <el-form label-width="140px">
          <el-form-item label="LOGO">
            <el-upload
              ref="upload"
              list-type="picture-card"
              action=""
              :on-change="handleChange"
              :file-list="fileList"
              :auto-upload="false"
              :limit="1"
              accept="image/*"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="小程序名称">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item>
            <el-button @click="saveHandler" type="primary">保存</el-button>
            <el-button @click="resetHandler">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped lang="scss">
.CardItems-box {
  background: #ffffff;
  padding: 20px;
  height: 100%;
}
</style>
